package itbour.onetouchshow.activity.challengezone.customvideopreview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.google.gson.Gson;
import com.lsjr.net.Encrypt;
import com.three.share.listener.ShareListener;
import com.utils.permission.Permission;
import com.xiao.nicevideoplayer.NiceVideoPlayer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.challengezone.ChallengeZoneActivity;
import itbour.onetouchshow.activity.version1_3.MainActivityV3;
import itbour.onetouchshow.base.BaseIJKPlayActivity;
import itbour.onetouchshow.bean.CustomVideoPreviewBean;
import itbour.onetouchshow.bean.HomeDetailslBean;
import itbour.onetouchshow.bean.JsShareBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.EdittextListener;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.listener.SoftKeyBoardListener;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.DateUtils;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.ShieldEmoji;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.ThirdAppInstall;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;
import itbour.onetouchshow.view.ActivityUtils;
import itbour.onetouchshow.widget.ChangeShareLinkStyleDialogFragment;
import itbour.onetouchshow.widget.LineEditText;
import itbour.onetouchshow.widget.UserProductShareDialogFragment;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


public class CustomVideoPreviewActivity extends BaseIJKPlayActivity<CustomVideoPreviewContract.View, CustomVideoPreviewPresenter> implements CustomVideoPreviewContract.View {

    /**
     * 提供取消
     */
    public OSSAsyncTask task;
    //名称
    @BindView(R.id.up_edit)
    protected LineEditText up_product_edit;
    @BindView(R.id.id_niceVideoPlayer)
    NiceVideoPlayer niceVideoPlayer;
    @BindView(R.id.id_tv_save_to_local)
    TextView idTvSaveToLocal;
    @BindView(R.id.tv_share_to_other)
    TextView tvShareToOther;
    @BindView(R.id.ll_download_share_container)
    LinearLayout llDownloadShareContainer;
    @BindView(R.id.id_user_make)
    LinearLayout idUserMake;
    @BindView(R.id.activity_detail_player)
    RelativeLayout activityDetailPlayer;
    @BindView(R.id.product_name)
    TextView proudctName;
    CustomVideoPreviewBean customVideoPreviewBean;
    OneToucDialog oneToucDialog;
    private String docId;

    public static Intent getLaunchIntent(Context context, String docId, String tag) {
        Intent intent = new Intent(context, CustomVideoPreviewActivity.class);
        intent.putExtra(AppConst.DOCID, docId);
        intent.putExtra(AppConst.TYPE_QA, tag);
        return intent;
    }

    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    public static Boolean hideInputMethod(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return false;
    }

    @Override
    public void loadSucceed(String result) {
        showContentView();
        customVideoPreviewBean = new Gson().fromJson(result, CustomVideoPreviewBean.class);
        onStartPlay(customVideoPreviewBean.getVideo().getVideoUrl(), "");
        String docNm = customVideoPreviewBean.getDocNm();
        if (docNm != null) {
            proudctName.setText(docNm);
            up_product_edit.setText(docNm);
        }

    }


    @Override
    public void setVideoHight() {

        if (customVideoPreviewBean.getVideo().getH() * 1.0 / customVideoPreviewBean.getVideo().getW() == 1) {
            ViewGroup.LayoutParams layoutParams = getmNiceVideoPlayer().getLayoutParams();
            layoutParams.width = UIUtils.WHD()[0];
            layoutParams.height = layoutParams.width;
            getmNiceVideoPlayer().setLayoutParams(layoutParams);
        } else if (customVideoPreviewBean.getVideo().getH() * 1.0 / customVideoPreviewBean.getVideo().getW() * 1.0 == 16 * 1.0 / 9) {
//            layoutParams.width = customVideoPreviewBean.getVideo().getW();
//            layoutParams.height = customVideoPreviewBean.getVideo().getH();
        } else if (customVideoPreviewBean.getVideo().getH() * 1.0 / customVideoPreviewBean.getVideo().getW() == 9 * 1.0 / 16) {
            ViewGroup.LayoutParams layoutParams = getmNiceVideoPlayer().getLayoutParams();
            layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            layoutParams.height = customVideoPreviewBean.getVideo().getH();
            getmNiceVideoPlayer().setLayoutParams(layoutParams);
        }

    }

    @Override
    protected int videoHeight() {
        return customVideoPreviewBean.getVideo().getH();
    }


    @Override
    public void loadFaild(String error) {
        finish();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleText("作品预览");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_custom_video_preview;
    }

    public void downLoadVideoSuccess(String string) {
        dismissProgressDialog();
        OneToucDialog show = new OneToucDialog.Builder(this)
                .content("已成功下载到本地")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        Log.e("TAH", "点击确定");
                    }
                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();

    }

    @Override
    public void getCustomVideoConfigureResutl(String result, String docId) {
        mPresenter.getCustomVideodoccontent(docId);
    }

    @Override
    public void getCustomVideodoccontentResult(String result) {
        Intent launchIntent = ChallengeZoneActivity.getLaunchIntent(getApplication(), result);
        startActivity(launchIntent);
    }

    @Override
    public void getDownVideoUrlresult(String url) {
        dismissProgressDialog();
        showNewDialog();
        alidownLoadFile(url);
    }


    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        String type = null;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            docId = extras.getString(AppConst.DOCID);
            type = extras.getString(AppConst.TYPE_QA);
        }
        super.afterCreate(savedInstanceState);
        showLoadingView();
        mPresenter.newLoadDocPreview(docId);
        showEdittextSetting();

        if (type.equals(UserMakeTag.WORK.getTypeName())) {
            getToolBarView().getRightTextView().setText("修改");
            getToolBarView().getRightTextView().setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View v) {
                    mPresenter.getCustomVideoConfigure(docId + "");
                }
            });
            up_product_edit.setVisibility(View.GONE);
            getToolBarView().getRightTextView().setVisibility(View.VISIBLE);
        } else if (type.equals(UserMakeTag.MAKE.getTypeName())) {
            //getToolBarView().getRightTextView().setVisibility(View.GONE);
            getToolBarView().getRightTextView().setText("完成");
            getToolBarView().getRightTextView().setVisibility(View.VISIBLE);
            getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.popAllActivityUntillOne(MainActivityV3.class);
                }
            });
            proudctName.setVisibility(View.GONE);
            up_product_edit.setVisibility(View.VISIBLE);
        } else if (type.equals(UserMakeTag.DRAFT.getTypeName())) {
            getToolBarView().getRightTextView().setVisibility(View.GONE);
        }
    }

    @Override
    protected NiceVideoPlayer getmNiceVideoPlayer() {
        return niceVideoPlayer;
    }

    @OnClick({R.id.up_edit, R.id.id_tv_save_to_local, R.id.tv_share_to_other, R.id.ll_download_share_container, R.id.id_user_make, R.id.activity_detail_player})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.up_edit:
                break;
            case R.id.id_tv_save_to_local:
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        // T_.showToastReal("成功");
                        showProgressDialogWithText("获取下载地址...");
                        mPresenter.getDownVideoUrl(docId);
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //T_.showToastReal("拒绝");
                    }
                });
                break;
            case R.id.tv_share_to_other:
                //分享
                ThirdAppInstall.cheackThirdPartIsInstall(getViewContext());
                if (ThirdAppInstall.isOnePartInstall()) {
                    showShareDialog();
                } else {
                    T_.showCustomToast("请安装微信或QQ或微博~");
                }
                break;
            case R.id.ll_download_share_container:
                break;
            case R.id.id_user_make:
                break;
            case R.id.activity_detail_player:
                break;
        }
    }

    @Override
    protected boolean isLoopPlay() {
        return false;
    }

    public void alidownLoadFile(String videoUrl) {
        L_.e(videoUrl);
        //  String url="http://itbour-generate.itbour.com/video/U25/2018/03/29/114530009_wtIedfgAqiYG1TJmHWFM/0.mp4";
        String path = Environment.getExternalStorageDirectory() + "/OneTouchShow";
        L_.e(path);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String name = DateUtils.getYMD() + FileUtils.getFileName(videoUrl);
        path = path + File.separator + name;
        path = path.replaceAll("//", "/");
        File futureStudioIconFile = new File(path);

        L_.e(futureStudioIconFile.getAbsolutePath() + "文件绝对路径");

        String key = videoUrl.replace("http://itbour-generate.itbour.com/", "");
        //  http://itbour-generate.itbour.com/
        GetObjectRequest get = new GetObjectRequest(AppConst.OSSDOWNBUCKETNAME, key);//设置下载进度回调
        //设置下载进度回调
        String finalPath = path;
        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                OSSLog.logDebug("getobj_progress: " + currentSize + "  total_size: " + totalSize, false);
                L_.e("getobj_progress: " + currentSize + "  total_size: " + totalSize);
                L_.e("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (currentSize * 100 / totalSize);
                L_.e(progress + "% ");
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        oneToucDialog.setTvprogress(progress + "% ");
                        oneToucDialog.setDownloadProgress(progress);
                    }
                });
            }
        });
        task = App.ossClient.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                FileOutputStream outputStream = null;
                // 请求成功
                InputStream inputStream = result.getObjectContent();
                byte[] fileReader = new byte[1024];
                int fileSizeDownloaded = 0;
                try {
                    outputStream = new FileOutputStream(futureStudioIconFile);
                    while ((fileSizeDownloaded = inputStream.read(fileReader)) != -1) {
                        // 处理下载的数据
                        outputStream.flush();
                        outputStream.write(fileReader, 0, fileSizeDownloaded);
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    Observable.just(finalPath).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
                        public void call(String aLong) {
                            T_.showToastReal("下载成功" + finalPath);
                            oneToucDialog.dismiss();
                            downLoadVideoSuccess(finalPath);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    oneToucDialog.dismiss();
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                oneToucDialog.dismiss();
            }
        });
        //取消
        // task.cancel();

    }

    public void showNewDialog() {
        requestPermission(new PermissionListener() {
            @Override
            public void onGranted() {
                // T_.showToastReal("成功");
                OneToucDialog.Builder builder = new OneToucDialog.Builder(CustomVideoPreviewActivity.this);
                builder.content("正在下载");
                oneToucDialog = builder.neutralText("取消").onNeutral(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        task.cancel();
                    }
                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                        .cancelable(true).setShowDownloadProgress(true).setmWidth(AppConst.APP_DIALOG_WIDTH)
                        .show();
            }

            @Override
            public void onDenied(List<String> list) {
                //T_.showToastReal("拒绝");
            }
        }, Permission.Group.STORAGE);
    }


    //修改了分享样式
    private void showShareDialog() {
        UserProductShareDialogFragment productShareDialog = new UserProductShareDialogFragment(ChangeShareLinkStyleDialogFragment.DialogType.TYPEOFCUSTOMVIDEO);
        JsShareBean jsShareBean = new JsShareBean();
        String shareTitle = PreferencesHelper.getData(AppConst.KEY_CUSTOM_SHARE_TITLE);
        String shareContent = PreferencesHelper.getData(AppConst.KEY_APP_SHARE_CONTENT);
        //HomeDetailslBean basicInfo = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class);
        HomeDetailslBean.AppControl appControl = InchingDataSingleCase.INSTANCE.getAppControl();
        if (TextUtils.isEmpty(shareTitle) && appControl != null) {
            shareTitle = appControl.getCustomVideoShareTitle();
        }
        if (TextUtils.isEmpty(shareContent) && appControl != null) {
            shareContent = appControl.getCustomVideoShareMsg();
        }
        jsShareBean.setTitle(shareTitle);
        jsShareBean.setContent(shareContent);
        CustomVideoPreviewBean.VideoBean video = customVideoPreviewBean.getVideo();
        if (video != null && video.getThumbs().get(0) != null) {
            if (!TextUtils.isEmpty(video.getThumbs().get(0))) {
                jsShareBean.setThumb(video.getThumbs().get(0));
            }
        } else {
            if (video.getThumbs() != null && video.getThumbs().size() > 0) {
                jsShareBean.setThumb(video.getThumbs().get(0));
            }
        }
        List<Long> list = new ArrayList<>();
        list.add(Long.valueOf(docId));
        list.add(Long.valueOf(App.getUserId()));
        String encrpty = Encrypt.shareCustomEncryptNumbers(list);
        String baseShareUrl = AppConfig.CustomSHARE;
        String shareUrl = baseShareUrl + encrpty;
        jsShareBean.setUrl(shareUrl);

        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                T_.showToastReal("分享成功");
            }

            @Override
            public void shareFailure(Exception e) {
                T_.showToastReal("分享失败" + e.getMessage());
            }

            @Override
            public void shareCancel() {
                T_.showToastReal("取消分享");
            }
        };
        //修改链接样式点击事件
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChangeShareLinkStyleDialogFragment styleDialogFragment = new ChangeShareLinkStyleDialogFragment(ChangeShareLinkStyleDialogFragment.DialogType.TYPEOFCUSTOMVIDEO);
                styleDialogFragment.onShow(CustomVideoPreviewActivity.this);
                styleDialogFragment.setOnDismissListener(new ChangeShareLinkStyleDialogFragment.onDismissListener() {
                    @Override
                    public void onDismiss() {
                        productShareDialog.updateTitleAndContent();
                    }
                });
            }
        };
        productShareDialog.setData(jsShareBean, shareListener, onClickListener);
        productShareDialog.onShow(CustomVideoPreviewActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        cleanEditTextFocus();
    }

    public void cleanEditTextFocus() {
        up_product_edit.clearFocus();
    }

    public void showEdittextSetting() {
        //rwb：取消EditText焦点，并且隐藏输入法。
        SoftKeyBoardListener.setListener(CustomVideoPreviewActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                //L_.i("键盘隐藏 高度" + height);
                if (!TextUtils.isEmpty(up_product_edit.getText().toString()) && up_product_edit.getText().length() > 0) {
                    // mPresenter.deleteVideoBg(up_product_edit.getText().toString());
                    mPresenter.doReNameWork(docId + "", up_product_edit.getText().toString());
                }
                cleanEditTextFocus();
            }
        });

        up_product_edit.setFilters(new InputFilter[]{/*new InputFilter.LengthFilter(value.getMax()), */new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                Matcher matcher = ShieldEmoji.isEmoji().matcher(charSequence);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        }});
        // up_product_edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10), filter});
        //限制输入
        EdittextListener edittextListener = new EdittextListener(up_product_edit, AppConst.editTextMaxLength) {
            @Override
            public void afterTextChanged(Editable editable) {
                super.afterTextChanged(editable);
            }
        };
        up_product_edit.addTextChangedListener(edittextListener);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                if (hideInputMethod(this, v)) {
                    cleanEditTextFocus();
                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

}
